package com.quanquan.management.service;


import DTO.PageDTO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.quanquan.management.dto.SignInDTO;
import com.quanquan.management.dto.UserDTO;
import com.quanquan.management.entity.SysUser;
import com.quanquan.management.request.IntegralDetailsRequestBody;
import com.quanquan.management.request.UserRequestBody;
import entity.ExcelData;
import enums.ResCodeEnum;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import request.PageRequestBody;
import utils.*;
import web.response.ResultBody;

import javax.servlet.http.HttpServletResponse;
import java.util.LinkedList;
import java.util.List;


/**
 * @author gongzhou
 * @title: ModuleService
 * @projectName SpringCloud
 * @description: TODO
 * @date 2019/3/289:33
 */
@Service
public class UserService {

    public static final String PUBLIC_NUMBER = "public_number";
    @Value("${module-url.userUrl}")
    private String userUrl;
    @Autowired
    private IntegralTradingService integralTradingService;

    public ResultBody create(UserRequestBody requestBody) {
        String json = Request.postJson(userUrl + "user/register",requestBody);
        if (StringUtil.isEmpty(json)) {
            return new ResultBody(ResCodeEnum.FAIL.getCode(),ResCodeEnum.FAIL.getMsg());
        }
        JSONObject jsonObject = JSON.parseObject(json);
        Integer resCode = jsonObject.getInteger("resCode");
        if (0 == resCode) {
            return new ResultBody(ResCodeEnum.SUCCESS.getCode(),ResCodeEnum.SUCCESS.getMsg());
        }
        if (-1 == resCode) {
            return new ResultBody(ResCodeEnum.FAIL.getCode(),ResCodeEnum.FAIL.getMsg());
        }
        return new ResultBody(-2,"用户已存在");

    }

    public UserDTO findById(String id) {
        UserRequestBody requestBody = new UserRequestBody();
        requestBody.setUserId(id);
        String json = Request.postJson(userUrl + "user/edit",requestBody);
        UserDTO userDTO = new UserDTO();
        JSONObject jsonObject = JSON.parseObject(json);
        Integer resCode = jsonObject.getInteger("resCode");
        if (0 == resCode) {
            userDTO = jsonObject.getJSONObject("data").toJavaObject(UserDTO.class);
        }
        return userDTO;
    }

    public UserDTO findByMobile(String mobile) {
        UserRequestBody requestBody = new UserRequestBody();
        requestBody.setPhone(mobile);
        String json = Request.postJson(userUrl + "user/get_by_phone",requestBody);
        UserDTO userDTO = null;
        JSONObject jsonObject = JSON.parseObject(json);
        Integer resCode = jsonObject.getInteger("resCode");
        if (0 == resCode ||10025 ==resCode) {
            userDTO = jsonObject.getJSONObject("data").toJavaObject(UserDTO.class);
        }
        return userDTO;
    }

    public UserDTO freeze(String userId) {
        UserRequestBody requestBody = new UserRequestBody();
        requestBody.setUserId(userId);
        String json = Request.postJson(userUrl + "user/frozen_account",requestBody);
        JSONObject jsonObject = JSON.parseObject(json);
        UserDTO userDTO = null;
        Integer resCode = jsonObject.getInteger("resCode");
        if (0 == resCode) {
            userDTO = jsonObject.getJSONObject("data").toJavaObject(UserDTO.class);
        }
        return userDTO;
    }

    public boolean update(UserRequestBody requestBody) {
        String id = requestBody.getId();
        String userId = requestBody.getUserId();
        if (StringUtil.isEmpty(id) && StringUtil.isNotEmpty(userId)) {
            requestBody.setId(userId);
        }
        if (StringUtil.isEmpty(userId) && StringUtil.isNotEmpty(id)) {
            requestBody.setUserId(id);
        }
        UserDTO dto = this.findById(requestBody.getUserId());
        //新积分
        Integer option = requestBody.getIntegral();
        //原来的积分
        Integer originInt = dto.getIntegral();
        if (null != option) {
            originInt = originInt + option;
            IntegralDetailsRequestBody integralDetailsRequestBody = new IntegralDetailsRequestBody();
            integralDetailsRequestBody.setIntegralPoint(Integer.toString(Math.abs(option)));
            integralDetailsRequestBody.setUserId(requestBody.getUserId());
            integralDetailsRequestBody.setTradeAction(option > 0 ? 0 : 1);
            integralDetailsRequestBody.setConsumeType("admin");
            integralDetailsRequestBody.setSource("admin");
            SysUser sysUser = (SysUser)SecurityUtils.getSubject().getPrincipal();
            integralDetailsRequestBody.setForeignKeyId(sysUser.getId());
            integralDetailsRequestBody.setOrderNum(UUIDGenerator.getUUID());
            integralDetailsRequestBody.setTradingContent(requestBody.getTradingContent());
            integralTradingService.record(integralDetailsRequestBody);
        }
        requestBody.setIntegral(originInt);
        String json = Request.postJson(userUrl + "user/update",requestBody);
        JSONObject jsonObject = JSON.parseObject(json);
        Integer resCode = jsonObject.getInteger("resCode");
        return 0 == resCode;
    }

    public PageDTO<UserDTO> list(UserRequestBody requestBody) {
        String json = Request.postJson(userUrl + "user/query_select", requestBody);
        PageDTO<UserDTO> pageDTO = new PageDTO<>();
        JSONObject jsonObject = JSON.parseObject(json);
        Integer resCode = jsonObject.getInteger("resCode");
        if (0 == resCode) {
            JSONObject jsonData = jsonObject.getJSONObject("data");
            PageDTO data = jsonObject.getJSONObject("data").toJavaObject(PageDTO.class);
            JSONArray list = jsonData.getJSONArray("list");
            List<UserDTO> userDTOS = new LinkedList<>();
            for (int i = 0; i < list.size(); i++ ) {
                UserDTO object = list.getObject(i, UserDTO.class);
                userDTOS.add(object);
            }
            data.setList(userDTOS);
            return data;
        }
        return pageDTO;
    }

    public void export(HttpServletResponse response,UserRequestBody requestBody) throws Exception {
        List<String> titles = new LinkedList<>();
        titles.add("卡号");
        titles.add("用户名");
        titles.add("姓名");
        titles.add("会员等级");
        titles.add("性别");
        titles.add("手机号");
        titles.add("积分");
        titles.add("注册来源");
        titles.add("注册时间");
        ExcelData data = ExcelUtil.getExcelData();
        data.setTitles(titles);
        PageDTO<UserDTO> pageDTO = this.list(requestBody);
        List<UserDTO> list = pageDTO.getList();
        List<List<Object>> rows = new LinkedList<>();
        list.forEach(userDTO -> {
            List<Object> row = new LinkedList<>();
            row.add(userDTO.getMemberCardNum());
            row.add(userDTO.getMemberName());
            row.add(userDTO.getName());
            row.add(userDTO.getMembeType());
            if(userDTO.getGender().toString().equals("0")){
                row.add("男");
            }else if(userDTO.getGender().toString().equals("1")){
                row.add("女");
            }
            else{
                row.add("保密");
            }
            row.add(userDTO.getPhone());
            row.add(userDTO.getIntegral().toString());
            if(userDTO.getSource().equals(PUBLIC_NUMBER)){
            row.add("微信公众号");
            }else{
                row.add("其他");
            }
            row.add(userDTO.getCreateTime());
            rows.add(row);
        });
        data.setRows(rows);
        ExcelUtil.exportExcel(response,"用户信息表-" + DateUtils.currentDate(DateUtils.DATE_HOUR_SECOND),data);
    }

    public PageDTO<SignInDTO> signInPageList(PageRequestBody requestBody) {
        String json = Request.postJson(userUrl + "sign/query_condition", requestBody);
        JSONObject jsonObject = JSON.parseObject(json);
        JSONObject jsonData = jsonObject.getJSONObject("data");
        PageDTO data = jsonObject.getJSONObject("data").toJavaObject(PageDTO.class);
        JSONArray list = jsonData.getJSONArray("list");
        List<SignInDTO> signInDTOS = new LinkedList<>();
        for (int i = 0; i < list.size(); i++ ) {
            SignInDTO object = list.getObject(i, SignInDTO.class);
            signInDTOS.add(object);
        }
        data.setList(signInDTOS);
        return data;
    }

    public void exportSign(HttpServletResponse response,PageRequestBody requestBody) throws Exception {
        List<String> titles = new LinkedList<>();
        titles.add("卡号");
        titles.add("手机号");
        titles.add("用户名");
        titles.add("积分");
        titles.add("时间");
        ExcelData data = ExcelUtil.getExcelData();
        data.setTitles(titles);
        PageDTO<SignInDTO> pageDTO = this.signInPageList(requestBody);
        List<SignInDTO> list = pageDTO.getList();
        List<List<Object>> rows = new LinkedList<>();
        list.forEach(dto -> {
            List<Object> row = new LinkedList<>();
            row.add(dto.getMemberCardNum());
            row.add(dto.getPhone());
            row.add(dto.getMemberName());
            row.add(dto.getIntegral() == null ? "暂无记录" : dto.getIntegral().toString());
            row.add(dto.getCreateTime());
            rows.add(row);
        });
        data.setRows(rows);
        ExcelUtil.exportExcel(response,"用户签到表-" + DateUtils.currentDate(DateUtils.DATE_HOUR_SECOND),data);
    }

}
